package com.example.androidmainshixun.presenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.example.androidmainshixun.R;
import com.example.androidmainshixun.base.WeakRefHandler;
import com.example.androidmainshixun.contract.MainContract;
import com.example.androidmainshixun.entity.Goods;

import java.util.ArrayList;
import java.util.List;

public class MainPresenter implements MainContract.IMainPresenter {

   private static final int WHAT_GET_GOODS_LIST = 1;// 定义常量
   private MainContract.IMainView mMainView;

   public MainPresenter(MainContract.IMainView mainView) {
      mMainView = mainView;
   }

   @Override
   public void getGoodsList() {
      // 创建一个列表来存储多个物品信息
      List<Goods> list = new ArrayList<>();
      new Thread(new Runnable() {
         @Override
         public void run() {
            //此处异步进行数据查询
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
               // 记录异常
               Thread.currentThread().interrupt(); // 恢复中断状态
            }

            list.add(new Goods("黄瓜", 1.28,  R.drawable.v1));
            list.add(new Goods("西红柿", 2.16, R.drawable.v2));
            list.add(new Goods("橙子", 2.03, R.drawable.f1));
            list.add(new Goods("橄榄调和油", 37.57, R.drawable.v11));
            list.add(new Goods("桃子", 2.18,  R.drawable.f5));
            list.add(new Goods("水果玉米", 2.03,  R.drawable.v4));
            list.add(new Goods("馒头", 5.86,  R.drawable.v12));
            list.add(new Goods("丝瓜", 8.4, R.drawable.v5));
            list.add(new Goods("五常大米", 12.98,  R.drawable.v13));
            list.add(new Goods("彩椒", 3.29,  R.drawable.v6));
            list.add(new Goods("大蒜", 4.9,  R.drawable.v8));
            list.add(new Goods("芦笋", 9.59, R.drawable.v7));
            list.add(new Goods("紫薯", 2.03, R.drawable.v10));
            list.add(new Goods("红薯尖", 10.69, R.drawable.v9));

            //子线程通过Handler发送消息，完成线程之间的通信。
            Message message = Message.obtain();
            message.obj = list;
            message.what = WHAT_GET_GOODS_LIST;
            mHandler.sendMessage(message);

         }

      }).start();
   }

   Handler mHandler = new WeakRefHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
      @Override
      public boolean handleMessage(@NonNull Message msg) {
         int what = msg.what;
         switch (what) {
            case WHAT_GET_GOODS_LIST:
               mMainView.showGoodsList((List<Goods>) msg.obj);
               break;
         }
         return false;
      }
   });
}

